import vm from '@/main'

const app = {
  state: {
    caches: JSON.parse(localStorage.getItem('template_caches')) || [],
    options: [],
    activeIndex: '/',
    isRouterAlive: true
  },
  mutations: {
    SET_CACHES: (state, caches) => {
      state.caches = caches
      localStorage.setItem('template_caches', JSON.stringify(caches))
    },
    ADD_CACHE: (state, cache) => {
      state.caches.includes(cache) || state.caches.push(cache)
      localStorage.setItem('template_caches', JSON.stringify(state.caches))
    },
    DEL_CACHE: (state, cache) => {
      let index = state.caches.indexOf(cache)
      index !== -1 && state.caches.splice(index, 1)
      localStorage.setItem('template_caches', JSON.stringify(state.caches))
    },
    ADD_TAB (state, params) {
      let { route, idx } = params
      state.options.filter(opt => opt.path === route.path).length || state.options.splice(idx, 0, Object.assign({ title: route.meta.title }, route))
      route.meta && !route.meta.noCache && !state.caches.includes(route.path) && this.commit('ADD_CACHE', route.path)
    },
    DEL_TAB (state, path) {
      let index = 0
      for (let option of state.options) {
        if (option.path === path) {
          option.meta && !option.meta.noCache && !option.meta.keepAlive && this.commit('DEL_CACHE', option.path)
          break
        }
        index++
      }
      state.options.splice(index, 1)
    },
    SET_ACTIVE_INDEX (state, index) {
      state.activeIndex = index
    },
    RELOAD (state) {
      state.isRouterAlive = false
      vm.$nextTick(() => { state.isRouterAlive = true })
    }
  }
}

export default app
